﻿using FieldTools.Client.Business.IBusiness;
using FieldTools.Client.Business.Util;
using FieldTools.Client.Entity.MyQQ;
using FieldTools.Client.Model.Window;
using FieldTools.Client.Entity.OneBot;
using FieldTools.Util;
using FieldTools.Util.Helper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace FieldTools.Client.Business.Business
{
    public partial class OneBotServerApiBus : BaseBus, IOneBotServerApiBus, ITransientDependency
    {
        public OneBotServerApiBus() { }

        #region 外部请求

        /// <inheritdoc/>
        public async Task<QuickHandleMessageInfo> HandleMessageInfoAsync(OneBotEnevtMessageInfo? oneBotEnevtMessageInfo)
        {
            //权限过滤
            var myqq = GetEntityConfig<MyQQModel>(nameof(MyQQModel), new());
            if (oneBotEnevtMessageInfo == null || myqq.RobotMasters == null)
            {
                return null;
            }
            if (!myqq.RobotMasters.Any(item => item.MasterQQ.Equals(oneBotEnevtMessageInfo.UserId.ToString()) && item.RobotQQ.Equals(oneBotEnevtMessageInfo.SelfId.ToString())))
            {
                return null;
            }
            //Console.WriteLine(oneBotEnevtMessageInfo?.ToJson());
            
            if(oneBotEnevtMessageInfo.SubType == "friend")
            {
                //关键字处理，分词处理todo new Regex(@"\{(\w+)\}");//大括号内的数据
                return await HandleKeyWordAsync(oneBotEnevtMessageInfo.RawMessage);
            }
            else if(oneBotEnevtMessageInfo.SubType == "group")
            {

            }
            else
            {

            }
            return null;
        }

        /// <inheritdoc/>
        public async Task<QuickHandleMetaInfo> HandleMetaInfoAsync(OneBotEventMetaInfo? oneBotEventMetaInfo)
        {
            Console.WriteLine(oneBotEventMetaInfo?.ToJson());
            return null;
        }

        /// <inheritdoc/>
        public async Task<QuickeHandleNoticeInfo> HandleNoticeInfoAsync(OneBotEventNoticeInfo? oneBotEventNoticeInfo)
        {
            Console.WriteLine(oneBotEventNoticeInfo?.ToJson());
            return null;
        }

        /// <inheritdoc/>
        public async Task<QuickeHandleRequestInfo> HandleRequestInfoAsync(OneBotEventRequestInfo? oneBotEventRequestInfo)
        {
            Console.WriteLine(oneBotEventRequestInfo?.ToJson());
            return null;
        }
        #endregion

        #region 内部方法
        /// <summary>
        /// 处理关键字，构建快速返回参数
        /// </summary>
        /// <param name="message"></param>
        /// <param name="matchType">匹配模式，0完全匹配（默认），1部分匹配</param>
        /// <returns></returns>
        private static async Task<QuickHandleMessageInfo> HandleKeyWordAsync(string message, int matchType=0)
        {
            if (string.IsNullOrEmpty(message)) return null;
            //预定义测试用
            if (matchType == 0 ? message == "fulitu2" : message.Contains("fulitu2"))
            {
                var url = await UtilHttpApi.GetBuyersShow();
                return new QuickHandleMessageInfo()
                {
                    Reply = $"[CQ:image,file={url}]"
                };
            }
            QuickHandleMessageInfo resInfo = new();
            var resMes = "";
            //机器人配置
            var myqq = GetEntityConfig<MyQQModel>(nameof(MyQQModel), new());
            //预定义字段替换
            var predefineContents = MyQQModel.PredefineContents;
            if (predefineContents != null && predefineContents.PredefineContentItems.Count >0)
            {
                Regex regex = BraceRegex();
                var matches = regex.Matches(message);
                foreach (Match match in matches.Cast<Match>())
                {
                    if (match.Success)
                    {
                        var value = match.Value;
                        var item = predefineContents.GetContentByField(value);
                        if(item!=null && !string.IsNullOrEmpty(item.ScriptContent) && item.IsOn)
                        {
                            var res = CShapeScriptHepler.ExcuteScript(item.ScriptContent, null);
                            message = message.Replace("{"+value+"}", res.ToJson());
                            resMes += res;
                        }
                    }
                }
            }
            
            //自定义回复
            var customOrders = myqq.CustonOrders;
            if (customOrders != null && customOrders.Any(item=>item.Keyword.Equals(message)))
            {
                var orderData = customOrders.First(item => item.Keyword.Equals(message));
                var analysisRes = orderData.Excute();
                resMes = analysisRes;
            }
            resInfo.Reply = string.IsNullOrEmpty(resMes) ? null : resMes;
            return resInfo;
        }

        /// <summary>
        /// 花括号包括的正则表达式，编译时生成，减少后续执行时间
        /// </summary>
        /// <returns></returns>
        [GeneratedRegex(@"(?i)(?<=\{)(.*?)(?=\})", RegexOptions.None, "zh-CN")]
        private static partial Regex BraceRegex();
        #endregion
    }
}
